package kr.co.hk.depart;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import kr.co.hk.R;

import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;


public class HyunList extends ListActivity {

	private String title = "";
	private String link = "";
	private String imageLink = "";
	private String date = "";
	private String urls;
	private Spinner spn;
	private String hyunCode1;
	private String hyunCode2;
	
	private ArrayList<String> imageUrl = new ArrayList<String>();
	private ArrayList<String> content = new ArrayList<String>();
	private ArrayList<String> content2 = new ArrayList<String>();
	private ArrayList<MyItemh> aMyItem = new ArrayList<MyItemh>();
	private ArrayList<String> addresses = new ArrayList<String>();
	private MyListAdapterh MyAdapter;
	private ProgressDialog progressDialog;
	final private int PROGRESS_DIALOG = 0;
	private boolean pageEx = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.hyun_list);
		
		
		spn = (Spinner) findViewById(R.id.hyunspn);
		ArrayAdapter spAdapter = ArrayAdapter.createFromResource(this, R.array.hyunname, android.R.layout.simple_spinner_item);
		spAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spn.setAdapter(spAdapter);
		
		MyAdapter = new MyListAdapterh(this, R.layout.date_row, aMyItem);
		setListAdapter(MyAdapter);
		
        spn.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int spPosition, long arg3) {
				imageUrl.clear();
				content.clear();
				content2.clear();
				aMyItem.clear();
				addresses.clear();
				
				Resources resources = getResources();
				String[] code1 = resources.getStringArray(R.array.hyuncode1);
				String[] code2 = resources.getStringArray(R.array.hyuncode2);
				
				hyunCode1 = code1[spPosition];
				hyunCode2 = code2[spPosition];
				urls = "http://www.ehyundai.com/newPortal/DP/DP000300_I.jsp?pSearchData=&pSiteMapId="+hyunCode1+"&pSearchSelect=&pCurrentPage=1&branchCd="+hyunCode2+"&swfseq=0200";
				mainProcessing();
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
        	
		});
        

        
        getListView().setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				String url = addresses.get(position);
				Intent intent = new Intent(HyunList.this, HyunDetail.class);
				intent.putExtra("url", url);

				startActivity(intent);
				
			}
		});
        
	}
	
	private Handler chdHandler = new Handler();

	private void mainProcessing() {
		pageEx = false;
		showDialog(PROGRESS_DIALOG);
		Thread childThread = new Thread(null, dobackgroundThreadProcessing,
				"Backgroud");
		childThread.start();
	}

	private Runnable dobackgroundThreadProcessing = new Runnable() {

		@Override
		public void run() {
			backgroudnThreadProcessing();
		}
	};

	private void backgroudnThreadProcessing() {
		getDateList(urls);
		chdHandler.post(doUpdateGUI);
	}

	private Runnable doUpdateGUI = new Runnable() {
		@Override
		public void run() {
			updateGUI();
		}
	};

	private void updateGUI() {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		progressDialog.dismiss();
		HyunList.this.removeDialog(PROGRESS_DIALOG);
		if(pageEx){
			excePro();
		}else{
			addItem();
			MyAdapter.notifyDataSetChanged();	
		}
	}

	private void excePro() {
		toast("페이지 로딩시 오류가  있습니다. \n 네트워크 확인 후 다시 시도 하세요!");
		onBackPressed();
	}
	private void toast(String text) {
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}
	private void addItem(){
		for (int i = 0; i < imageUrl.size(); i++) {
			try {

				InputStream is = new URL(imageUrl.get(i)).openStream();

				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inScaled = false;
				Bitmap src = BitmapFactory.decodeStream(is, null, options);
				Bitmap resized;

				if (src != null) {
					int width = src.getWidth();
					int height = src.getHeight();
					resized = Bitmap.createScaledBitmap(src, width, height,
							true);
				} else {
					options.inScaled = false;
					resized = BitmapFactory.decodeStream(is, null, options);

				}

				MyItemh item = new MyItemh(resized, content.get(i), content2
						.get(i));
				aMyItem.add(item);
				

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case PROGRESS_DIALOG:

			progressDialog = new ProgressDialog(this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("Now loading..");
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(false);
			return progressDialog;

		}
		return null;

	}
	
	public void getDateList(String addr) {
		try {
			URL url = new URL(addr);
			System.out.println(addr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			if (conn != null) {
				conn.setConnectTimeout(10000);
				conn.setReadTimeout(10000);
				conn.setUseCaches(false);
				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					BufferedReader br = new BufferedReader(
							new InputStreamReader(conn.getInputStream(),
									"euc-kr"));
					ArrayList<String> list = new ArrayList<String>();
					String msg = "";
					while ((msg = br.readLine()) != null) {
						list.add(msg.trim() + "\n");
					}


					for (int i = 0; i < list.size(); i++) {


						String line = list.get(i);

						String reStr = line;
						int firstIndex = 0;
						int lastIndex = 0;
						
						
						if (line.contains(";\"><img")) {
							reStr = list.get(i);

							firstIndex = reStr.indexOf("/attachfiles");
							lastIndex = reStr.indexOf("\" w");

							imageLink = reStr.substring(firstIndex, lastIndex);
							imageLink = "http://www.ehyundai.com"+imageLink;
													

						}
						
						if (line.contains("class=\"title\"><a")) {
							reStr = list.get(i);
							
							firstIndex = reStr.indexOf(";\">");
							lastIndex = reStr.indexOf("</a>");
							title = reStr.substring(firstIndex+3, lastIndex).replace("amp;", "");
							
//							if (reStr.contains(";\"></a>")) {
//								reStr = list.get(i-1);
//								firstIndex = reStr.indexOf(";\">");
//								lastIndex = reStr.indexOf("</a>");
//								title = reStr.substring(firstIndex+3, lastIndex).replace("amp;", "");								
//							}

						}
						
						if (line.contains("class=\"tex\"><a")) {
							reStr = list.get(i);
							firstIndex = reStr.indexOf("ew(");
							lastIndex = reStr.indexOf(",'01");
							link = reStr.substring(firstIndex+3, lastIndex);
							link = "http://www.ehyundai.com/newPortal/DP/DP000100_L.jsp?pCurrentPage=1&pSeq="+link+"&DataSetExcute=N&pReg_dt=20100921135033&pSiteMapId=0101120200&swfseq=0200&pBoardState=2";
													
						}		
						
						if (line.contains("class=\"info\"")) {
							reStr = list.get(i+3);

							firstIndex = reStr.indexOf("<dd>");
							lastIndex = reStr.indexOf("</dd>");

							date = reStr.substring(firstIndex+4, lastIndex);
							
							imageUrl.add(imageLink);
							content.add(title);
							content2.add(date);
							addresses.add(link);
							

						}

					}
					br.close();
				}
				conn.disconnect();
				
			}
		} catch (Exception ex) {
			pageEx = true;
			ex.printStackTrace();

		}
	}

}

class MyItemh {
	Bitmap bits;
	String contents;
	String contents2;

	MyItemh(Bitmap bit, String content, String content2) {
		bits = bit;
		contents = content;
		contents2 = content2;
	}
}

class MyListAdapterh extends BaseAdapter {
	Context maincon;
	LayoutInflater Inflater;
	ArrayList<MyItemh> aitem;
	int alayout;

	public MyListAdapterh(Context context, int layout, ArrayList<MyItemh> item) {
		maincon = context;
		Inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		alayout = layout;
		aitem = item;
	}

	public int getCount() {
		return aitem.size();
	}

	public String getItem(int position) {
		return aitem.get(position).contents;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		final int pos = position;
		if (convertView == null) {
			convertView = Inflater.inflate(alayout, parent, false);
		}

		ImageView img = (ImageView) convertView.findViewById(R.id.dateRowImg);
		img.setImageBitmap(aitem.get(pos).bits);

		TextView tv = (TextView) convertView.findViewById(R.id.toptext);
		tv.setText(aitem.get(pos).contents);

		TextView tv1 = (TextView) convertView.findViewById(R.id.bottomtext);
		tv1.setText(aitem.get(pos).contents2);

		return convertView;
	}
}
